<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="UTF-8">
  <meta 
    name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <meta 
    http-equiv="X-UA-Compatible" 
    content="ie=edge">
  <meta 
    name="theme-color" 
    content="#fff" 
    id="theme-color">
  <meta 
    name="description" 
    content="hexoDemo用于介绍如何使用hexo">
  <link 
    rel="icon" 
    href="/">
  <title>04-Node.js模块化规范：CommonJS</title>
  
    
      <meta 
        property="og:title" 
        content="04-Node.js模块化规范：CommonJS">
    
    
      <meta 
        property="og:url" 
        content="https://zwl5670.gitee.io/2011/08/01/11-Node.js/04-Node.js%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83%EF%BC%9ACommonJS/index.html">
    
    
      <meta 
        property="og:img" 
        content="https://img.songhn.com/img/Y67gdd.png">
    
    
      <meta 
        property="og:img" 
        content="hexoDemo用于介绍如何使用hexo">
    
    
      <meta 
        property="og:type" 
        content="article">
      <meta 
        property="og:article:published_time" 
        content="2011-08-01">
      <meta 
        property="og:article:modified_time" 
        content="2023-03-14">
      <meta 
        property="og:article:author" 
        content="zwl5670">
      
        
          <meta 
            property="og:article:tag" 
            content="Node">
        
      
    
  
  
  <link rel="preload" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css" as="style" >
  <link rel="preload" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css" as="style" >
  <link rel="preload" href="/css/main.css" as="style" >
  
  <link rel="modulepreload" href="//instant.page/5.1.0">
  
  <link rel="stylesheet" href="/css/main.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css">
  
  
  
    <link rel="stylesheet" href="/js/lib/lightbox/baguetteBox.min.css">
  
  <script>
    function loadScript(url, cb) {
      var script = document.createElement('script');
      script.src = url;
      if (cb) script.onload = cb;
      script.async = true;
      document.body.appendChild(script);
    }
    function loadCSS(href, data, attr) {
      var sheet = document.createElement('link');
      sheet.ref = 'stylesheet';
      sheet.href = href;
      sheet.dataset[data] = attr;
      document.head.appendChild(sheet);
    }
    function changeCSS(cssFile, data, attr) {
      var oldlink = document.querySelector(data);
      var newlink = document.createElement("link");
      newlink.setAttribute("rel", "stylesheet");
      newlink.setAttribute("href", cssFile);
      newlink.dataset.prism = attr;
      document.head.replaceChild(newlink, oldlink);
    }
  </script>
  
    
  
  <script>
    // control reverse button
    var reverseDarkList = {
      dark: 'light',
      light: 'dark'
    };
    var themeColor = {
      dark: '#1c1c1e',
      light: '#fff'
    }
    // get the data of css prefers-color-scheme
    var getCssMediaQuery = function() {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    };
    // reverse current darkmode setting function
    var reverseDarkModeSetting = function() {
      var setting = localStorage.getItem('user-color-scheme');
      if(reverseDarkList[setting]) {
        setting = reverseDarkList[setting];
      } else if(setting === null) {
        setting = reverseDarkList[getCssMediaQuery()];
      } else {
        return;
      }
      localStorage.setItem('user-color-scheme', setting);
      return setting;
    };
    // apply current darkmode setting
  </script>
  
    <script>
      var setDarkmode = function(mode) {
      var setting = mode || localStorage.getItem('user-color-scheme');
      if(setting === getCssMediaQuery()) {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else if(reverseDarkList[setting]) {
        document.documentElement.setAttribute('data-user-color-scheme', setting);
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[getCssMediaQuery()];
        document.getElementById('theme-color').dataset.mode = getCssMediaQuery();
      }
    };
    setDarkmode();
    </script>
  
  
  
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.js" as="script">
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.css" as="style" >
  
  
    <link rel="preload" href="/js/lib/lozad.min.js" as="script">
  
  
  
  
  
  
<meta name="generator" content="Hexo 6.3.0"></head>

  <body>
    <div class="wrapper">
       
      <nav class="navbar">
  <div class="navbar-logo">
    <a class="navbar-logo-main" href="/">
      
      <span class="navbar-logo-dsc">前端面试</span>
      </a>
  </div>
  <div class="navbar-menu">
    
      <a 
        href="/" 
        class="navbar-menu-item">
        
          首页
        
      </a>
    
      <a 
        href="/archives" 
        class="navbar-menu-item">
        
          归档
        
      </a>
    
      <a 
        href="/tags" 
        class="navbar-menu-item">
        
          标签
        
      </a>
    
      <a 
        href="/categories" 
        class="navbar-menu-item">
        
          分类
        
      </a>
    
      <a 
        href="/about" 
        class="navbar-menu-item">
        
          关于
        
      </a>
    
      <a 
        href="/links" 
        class="navbar-menu-item">
        
          友链
        
      </a>
    
    <button 
      class="navbar-menu-item darknavbar navbar-menu-btn" 
      aria-label="Toggle dark mode"
      id="dark">
      <i class="iconfont icon-weather"></i>
    </button>
    <button 
      class="navbar-menu-item searchnavbar navbar-menu-btn" 
      aria-label="Toggle search"
      id="search">
      <!-- <i 
        class="iconfont icon-search" 
        style="font-size: 1.2rem; font-weight: 400;">
      </i> -->
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img"
        class="iconify iconify--ion" width="28" height="28" preserveAspectRatio="xMidYMid meet" viewBox="0 0 512 512">
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M256 80a176 176 0 1 0 176 176A176 176 0 0 0 256 80Z"></path>
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M232 160a72 72 0 1 0 72 72a72 72 0 0 0-72-72Z"></path>
        <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="28"
          d="M283.64 283.64L336 336"></path>
      </svg>
    </button>
  </div>
</nav> 
      
      <div 
        id="local-search" 
        style="display: none">
        <input
          class="navbar-menu-item"
          id="search-input"
          placeholder="请输入搜索内容..." />
        <div id="search-content"></div>
      </div>
      
      <div class="section-wrap">
        <div class="container">
          <div class="columns">
            <aside class="left-column">
              
              <div class="card card-author">
                
  <img 
    src="https://img.songhn.com/img/Y67gdd.png" 
    class="author-img"
    width="88"
    height="88"
    alt="author avatar">

<p class="author-name">zwl5670</p>
<p class="author-description">前端学习资料</p>
<div class="author-message">
  <a 
    class="author-posts-count" 
    href="/archives">
    <span>215</span>
    <span>文章</span>
  </a>
  <a 
    class="author-categories-count" 
    href="/categories">
    <span>14</span>
    <span>分类</span>
  </a>
  <a 
    class="author-tags-count" 
    href="/tags">
    <span>14</span>
    <span>标签</span>
  </a>
</div>

              </div>
               <div class="sticky-tablet">
  
  
    <article class="display-when-two-columns spacer">
      <div class="card card-content toc-card">
        <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-text">前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E7%9A%84%E7%90%86%E8%A7%A3"><span class="toc-text">模块化的理解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E6%A8%A1%E5%9D%97%E5%8C%96"><span class="toc-text">什么是模块化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E7%9A%84%E5%A5%BD%E5%A4%84"><span class="toc-text">模块化的好处</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83"><span class="toc-text">模块化规范</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83%E7%9A%84%E5%BC%95%E5%85%A5"><span class="toc-text">模块化规范的引入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E7%9A%84%E6%A6%82%E5%BF%B5%E8%A7%A3%E8%AF%BB"><span class="toc-text">模块化的概念解读</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83-1"><span class="toc-text">模块化规范</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CommonJS-%E7%9A%84%E5%9F%BA%E6%9C%AC%E8%AF%AD%E6%B3%95"><span class="toc-text">CommonJS 的基本语法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#CommonJS-%E7%9A%84%E4%BB%8B%E7%BB%8D"><span class="toc-text">CommonJS 的介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E7%9A%84%E6%9A%B4%E9%9C%B2%E5%92%8C%E5%BC%95%E5%85%A5"><span class="toc-text">模块的暴露和引入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9A%B4%E9%9C%B2%E6%A8%A1%E5%9D%97%E7%9A%84%E6%96%B9%E5%BC%8F%E4%B8%80%EF%BC%9A-exports"><span class="toc-text">暴露模块的方式一： exports</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9A%B4%E9%9C%B2%E6%A8%A1%E5%9D%97%E7%9A%84%E6%96%B9%E5%BC%8F%E4%BA%8C%EF%BC%9A-module-exports"><span class="toc-text">暴露模块的方式二： module.exports</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#exports-%E5%92%8C-module-exports-%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-text">exports 和 module.exports 的区别</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%97%AE%E9%A2%98-%E6%9A%B4%E9%9C%B2%E7%9A%84%E6%A8%A1%E5%9D%97%E5%88%B0%E5%BA%95%E6%98%AF%E8%B0%81%EF%BC%9F"><span class="toc-text">问题: 暴露的模块到底是谁？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%95%E5%85%A5%E6%A8%A1%E5%9D%97%E7%9A%84%E6%96%B9%E5%BC%8F%EF%BC%9Arequire"><span class="toc-text">引入模块的方式：require</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BB%E6%A8%A1%E5%9D%97"><span class="toc-text">主模块</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E7%9A%84%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-text">模块的初始化</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CommonJS-%E5%9C%A8%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%AB%AF%E7%9A%84%E5%AE%9E%E7%8E%B0%E4%B8%BE%E4%BE%8B"><span class="toc-text">CommonJS 在服务器端的实现举例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%88%9D%E5%A7%8B%E5%8C%96%E9%A1%B9%E7%9B%AE"><span class="toc-text">1、初始化项目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E5%AF%BC%E5%85%A5%E7%AC%AC%E4%B8%89%E6%96%B9%E5%8C%85"><span class="toc-text">2、导入第三方包</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E6%A8%A1%E5%9D%97"><span class="toc-text">3、自定义模块</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CommonJS-%E5%9F%BA%E4%BA%8E%E6%B5%8F%E8%A7%88%E5%99%A8%E7%AB%AF%E7%9A%84%E5%AE%9E%E7%8E%B0%E4%B8%BE%E4%BE%8B"><span class="toc-text">CommonJS 基于浏览器端的实现举例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%88%9D%E5%A7%8B%E5%8C%96%E9%A1%B9%E7%9B%AE-1"><span class="toc-text">1、初始化项目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E4%B8%8B%E8%BD%BD%E7%AC%AC%E4%B8%89%E6%96%B9%E5%8C%85%EF%BC%9ABrowserify"><span class="toc-text">2、下载第三方包：Browserify</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E6%A8%A1%E5%9D%97-amp-%E4%BB%A3%E7%A0%81%E8%BF%90%E8%A1%8C"><span class="toc-text">3、自定义模块 &amp; 代码运行</span></a></li></ol></li></ol>
      </div>
    </article>
  
  
  <article class="card card-content categories-widget">
    <div class="categories-card">
  <div class="categories-header">
    <i 
      class="iconfont icon-fenlei" 
      style="padding-right: 2px;">
    </i>分类
  </div>
  <div class="categories-list">
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/">
        <div class="categories-list-item">
          前端工具
          <span class="categories-list-item-badge">13</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          CSS基础
          <span class="categories-list-item-badge">18</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          CSS进阶
          <span class="categories-list-item-badge">9</span>
        </div>
      </a>
    
      <a href="/categories/HTML/">
        <div class="categories-list-item">
          HTML
          <span class="categories-list-item-badge">12</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          JS基础
          <span class="categories-list-item-badge">56</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80ES6/">
        <div class="categories-list-item">
          JS基础ES6
          <span class="categories-list-item-badge">10</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/">
        <div class="categories-list-item">
          JS基础异步
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/JS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          JS进阶
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/%E7%A7%BB%E5%8A%A8web/">
        <div class="categories-list-item">
          移动web
          <span class="categories-list-item-badge">3</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%92%8CDOM/">
        <div class="categories-list-item">
          CSS和DOM
          <span class="categories-list-item-badge">6</span>
        </div>
      </a>
    
      <a href="/categories/Node/">
        <div class="categories-list-item">
          Node
          <span class="categories-list-item-badge">16</span>
        </div>
      </a>
    
      <a href="/categories/Vue%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          Vue基础
          <span class="categories-list-item-badge">15</span>
        </div>
      </a>
    
      <a href="/categories/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/">
        <div class="categories-list-item">
          性能优化
          <span class="categories-list-item-badge">7</span>
        </div>
      </a>
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/">
        <div class="categories-list-item">
          前端工程化
          <span class="categories-list-item-badge">8</span>
        </div>
      </a>
    
  </div>
</div>
  </article>
  
  <article class="card card-content tags-widget">
    <div class="tags-card">
  <div class="tags-header">
    <i 
      class="iconfont icon-biaoqian" 
      style="padding-right: 2px;">
    </i>热门标签
  </div>
  <div class="tags-list">
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80/" 
        title="JS基础">
        <div class="tags-list-item">JS基础</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%9F%BA%E7%A1%80/" 
        title="CSS基础">
        <div class="tags-list-item">CSS基础</div>
      </a>
    
      <a 
        href="/tags/Node/" 
        title="Node">
        <div class="tags-list-item">Node</div>
      </a>
    
      <a 
        href="/tags/Vue%E5%9F%BA%E7%A1%80/" 
        title="Vue基础">
        <div class="tags-list-item">Vue基础</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/" 
        title="前端工具">
        <div class="tags-list-item">前端工具</div>
      </a>
    
      <a 
        href="/tags/HTML/" 
        title="HTML">
        <div class="tags-list-item">HTML</div>
      </a>
    
      <a 
        href="/tags/JS%E8%BF%9B%E9%98%B6/" 
        title="JS进阶">
        <div class="tags-list-item">JS进阶</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
        title="JS基础异步">
        <div class="tags-list-item">JS基础异步</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80ES6/" 
        title="JS基础ES6">
        <div class="tags-list-item">JS基础ES6</div>
      </a>
    
      <a 
        href="/tags/CSS%E8%BF%9B%E9%98%B6/" 
        title="CSS进阶">
        <div class="tags-list-item">CSS进阶</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/" 
        title="前端工程化">
        <div class="tags-list-item">前端工程化</div>
      </a>
    
      <a 
        href="/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" 
        title="性能优化">
        <div class="tags-list-item">性能优化</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%92%8CDOM/" 
        title="CSS和DOM">
        <div class="tags-list-item">CSS和DOM</div>
      </a>
    
      <a 
        href="/tags/%E7%A7%BB%E5%8A%A8web/" 
        title="移动web">
        <div class="tags-list-item">移动web</div>
      </a>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
            <main class="main-column">
              
<article class="card card-content">
  <header>
    <h1 class="post-title">
      04-Node.js模块化规范：CommonJS
    </h1>
  </header>
  <div class="post-meta post-show-meta">
    <time datetime="2011-07-31T16:00:00.000Z">
      <i 
        class="iconfont icon-calendar" 
        style="margin-right: 2px;">
      </i>
      <span>2011-08-01</span>
    </time>
    
      <span class="dot"></span>
      
        <a 
          href="/categories/Node/" 
          class="post-meta-link">
          Node
        </a>
      
    
    
      <span class="dot"></span>
      <span>4.1k 字</span>
    
  </div>
  
    <div 
      class="post-meta post-show-meta" 
      style="margin-top: -10px;">
      <div style="display: flex; align-items: center;">
        <i 
          class="iconfont icon-biaoqian" 
          style="margin-right: 2px; font-size: 1.15rem;">
        </i>
        
          
          <a 
            href="/tags/Node/" 
            class="post-meta-link">
            Node
          </a>
        
      </div>
    </div>
  
  </header>
  <div 
    id="section" 
    class="post-content">
    <p><ArticleTopAd></ArticleTopAd></p>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2><p>网站越来越复杂，js代码、js文件也越来越多，会遇到<strong>一些问题</strong>：</p>
<ul>
<li><p>文件依赖</p>
</li>
<li><p>全局污染、命名冲突</p>
</li>
</ul>
<p>程序模块化包括：</p>
<ul>
<li><p>日期模块</p>
</li>
<li><p>数学计算模块</p>
</li>
<li><p>日志模块</p>
</li>
<li><p>登陆认证模块</p>
</li>
<li><p>报表展示模块等。</p>
</li>
</ul>
<p>所有这些模块共同组成了程序软件系统。</p>
<p>一次编写，多次使用，才是提高效率的核心。</p>
<h2 id="模块化的理解"><a href="#模块化的理解" class="headerlink" title="模块化的理解"></a>模块化的理解</h2><h3 id="什么是模块化"><a href="#什么是模块化" class="headerlink" title="什么是模块化"></a>什么是模块化</h3><p><strong>概念</strong>：将一个复杂的程序依据一定的规则（规范）封装成几个块（文件），并组合在一起。</p>
<p>模块的内部数据、实现是私有的, 只是向外部暴露一些接口(方法)与外部其它模块通信。</p>
<p>最早的时候，我们会把所有的代码都写在一个js文件里，那么，耦合性会很高（关联性强），不利于维护；而且会造成全局污染，很容易命名冲突。</p>
<h3 id="模块化的好处"><a href="#模块化的好处" class="headerlink" title="模块化的好处"></a>模块化的好处</h3><ul>
<li><p>避免命名冲突，减少命名空间污染</p>
</li>
<li><p>降低耦合性；更好地分离、按需加载</p>
</li>
<li><p><strong>高复用性</strong>：代码方便重用，别人开发的模块直接拿过来就可以使用，不需要重复开发类似的功能。</p>
</li>
<li><p><strong>高可维护性</strong>：软件的声明周期中最长的阶段其实并不是开发阶段，而是维护阶段，需求变更比较频繁。使用模块化的开发，方式更容易维护。</p>
</li>
<li><p>部署方便</p>
</li>
</ul>
<h2 id="模块化规范"><a href="#模块化规范" class="headerlink" title="模块化规范"></a>模块化规范</h2><h3 id="模块化规范的引入"><a href="#模块化规范的引入" class="headerlink" title="模块化规范的引入"></a>模块化规范的引入</h3><p>假设我们引入模块化，首先可能会想到的思路是：在一个文件中引入多个js文件。如下：</p>
<pre class="highlight"><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;zepto.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;fastClick.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;util/login.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;util/base.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;util/city.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br></pre>

<p>但是这样做会带来很多问题：</p>
<ul>
<li><p>请求过多：引入十个js文件，就有十次http请求。</p>
</li>
<li><p>依赖模糊：不同的js文件可能会相互依赖，如果改其中的一个文件，另外一个文件可能会报错。</p>
</li>
</ul>
<p>以上两点，最终导致：<strong>难以维护</strong>。</p>
<p>于是，这就引入了模块化规范。</p>
<h3 id="模块化的概念解读"><a href="#模块化的概念解读" class="headerlink" title="模块化的概念解读"></a>模块化的概念解读</h3><p>模块化起源于 Node.js。Node.js 中把很多 js 打包成 package，需要的时候直接通过 require 的方式进行调用（CommonJS），这就是模块化的方式。</p>
<p>那如何把这种模块化思维应用到前端来呢？这就产生了两种伟大的 js：RequireJS 和 SeaJS。</p>
<h3 id="模块化规范-1"><a href="#模块化规范-1" class="headerlink" title="模块化规范"></a>模块化规范</h3><p>服务器端规范：</p>
<ul>
<li><a target="_blank" rel="noopener" href="http://www.commonjs.org/"><strong>CommonJS规范</strong></a>：是 Node.js 使用的模块化规范。</li>
</ul>
<p>CommonJS 就是一套约定标准，不是技术。用于约定我们的代码应该是怎样的一种结构。</p>
<p>浏览器端规范：</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://github.com/amdjs/amdjs-api"><strong>AMD规范</strong></a>：是 <strong><a target="_blank" rel="noopener" href="http://requirejs.org/">RequireJS</a></strong> 在推广过程中对模块化定义的规范化产出。</li>
</ul>
<pre class="highlight"><span class="line">- 异步加载模块；</span><br><span class="line"></span><br><span class="line">- 依赖前置、提前执行：require([`foo`,`bar`],function(foo,bar)&#123;&#125;);   //也就是说把所有的包都 require 成功，再继续执行代码。</span><br><span class="line"></span><br><span class="line">- define 定义模块：define([`require`,`foo`],function()&#123;return&#125;);</span><br></pre>

<ul>
<li>**<a href="">CMD规范</a>**：是 <strong><a target="_blank" rel="noopener" href="http://seajs.org/">SeaJS</a></strong> 在推广过程中对模块化定义的规范化产出。淘宝团队开发。</li>
</ul>
<pre class="highlight"><span class="line"></span><br><span class="line">同步加载模块；</span><br><span class="line"></span><br><span class="line">依赖就近，延迟执行：require(./a) 直接引入。或者Require.async 异步引入。   //依赖就近：执行到这一部分的时候，再去加载对应的文件。</span><br><span class="line"></span><br><span class="line">define 定义模块， export 导出：define(function(require, export, module)&#123;&#125;);</span><br></pre>


<p>PS：面试时，经常会问AMD 和 CMD 的区别。</p>
<p>另外，还有ES6规范：import &amp; export。</p>
<p>这篇文章，我们来讲一下<code>CommonJS</code>，它是 Node.js 使用的模块化规范。</p>
<h2 id="CommonJS-的基本语法"><a href="#CommonJS-的基本语法" class="headerlink" title="CommonJS 的基本语法"></a>CommonJS 的基本语法</h2><h3 id="CommonJS-的介绍"><a href="#CommonJS-的介绍" class="headerlink" title="CommonJS 的介绍"></a>CommonJS 的介绍</h3><p><a target="_blank" rel="noopener" href="http://www.commonjs.org/">CommonJS</a>：是 Node.js 使用的模块化规范。也就是说，Node.js 就是基于 CommonJS 这种模块化规范来编写的。</p>
<p>CommonJS 规范规定：每个模块内部，module 变量代表当前模块。这个变量是一个对象，它的 exports 属性（即 module.exports）是对外的接口对象。加载某个模块，其实是加载该模块的 module.exports 对象。</p>
<p>在 CommonJS 中，每个文件都可以当作一个模块：</p>
<ul>
<li><p>在服务器端：模块的加载是运行时同步加载的。</p>
</li>
<li><p>在浏览器端: 模块需要提前编译打包处理。首先，既然同步的，很容易引起阻塞；其次，浏览器不认识<code>require</code>语法，因此，需要提前编译打包。</p>
</li>
</ul>
<h3 id="模块的暴露和引入"><a href="#模块的暴露和引入" class="headerlink" title="模块的暴露和引入"></a>模块的暴露和引入</h3><p>Node.js 中只有模块级作用域，两个模块之间的变量、方法，默认是互不冲突，互不影响，这样就导致一个问题：模块 A 要怎样使用模块B中的变量&amp;方法呢？这就需要通过 <code>exports</code> 关键字来实现。</p>
<p>Node.js中，每个模块都有一个 exports 接口对象，我们可以把公共的变量、方法挂载到这个接口对象中，其他的模块才可以使用。</p>
<p>接下来详细讲一讲模块的暴露、模块的引入。</p>
<h3 id="暴露模块的方式一：-exports"><a href="#暴露模块的方式一：-exports" class="headerlink" title="暴露模块的方式一： exports"></a>暴露模块的方式一： exports</h3><p><code>exports</code>对象用来导出当前模块的公共方法或属性。别的模块通过 require 函数调用当前模块时，得到的就是当前模块的 exports 对象。</p>
<p><strong>语法格式</strong>：</p>
<pre class="highlight"><span class="line"><span class="comment">// 相当于是：给 exports 对象添加属性</span></span><br><span class="line"><span class="built_in">exports</span>.<span class="property">xxx</span> = value</span><br></pre>

<p>这个 value 可以是任意的数据类型。</p>
<p><strong>注意</strong>：暴露的关键词是<code>exports</code>，不是<code>export</code>。其实，这里的 exports 类似于 ES6 中的 export 的用法，都是用来导出一个指定名字的对象。</p>
<p><strong>代码举例</strong>：</p>
<pre class="highlight"><span class="line"><span class="keyword">const</span> name = <span class="string">&#x27;qianguyihao&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> foo = <span class="keyword">function</span> (<span class="params">value</span>) &#123;</span><br><span class="line">	<span class="keyword">return</span> value * <span class="number">2</span>;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="built_in">exports</span>.<span class="property">name</span> = name;</span><br><span class="line"><span class="built_in">exports</span>.<span class="property">foo</span> = foo;</span><br></pre>



<h3 id="暴露模块的方式二：-module-exports"><a href="#暴露模块的方式二：-module-exports" class="headerlink" title="暴露模块的方式二： module.exports"></a>暴露模块的方式二： module.exports</h3><p><code>module.exports</code>用来导出一个默认对象，没有指定对象名。</p>
<p>语法格式：</p>
<pre class="highlight"><span class="line"><span class="comment">// 方式一：导出整个 exports 对象</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = value;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方式二：给 exports 对象添加属性</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span>.<span class="property">xxx</span> = value;</span><br></pre>

<p>这个 value 可以是任意的数据类型。</p>
<p>代码举例：</p>
<pre class="highlight"><span class="line"><span class="comment">// 方式1</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = &#123;</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&#x27;我是 module1&#x27;</span>,</span><br><span class="line">    <span class="title function_">foo</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">name</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 我们不能再继续写 module.exports = value2。因为重新赋值，会把 exports 对象 之前的赋值覆盖掉。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 方式2</span></span><br><span class="line"><span class="keyword">const</span> age = <span class="number">28</span>;</span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span>.<span class="property">age</span> = age;</span><br><span class="line"></span><br></pre>

<p><code>module.exports</code> 还可以修改模块的原始导出对象。比如当前模块原本导出的是一个对象，我们可以通过 module.exports 修改为导出一个函数。如下：</p>
<pre class="highlight"><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;hello world&#x27;</span>)</span><br><span class="line">&#125;</span><br></pre>

<h3 id="exports-和-module-exports-的区别"><a href="#exports-和-module-exports-的区别" class="headerlink" title="exports 和 module.exports 的区别"></a>exports 和 module.exports 的区别</h3><p>最重要的区别：</p>
<ul>
<li><p>使用exports时，只能单个设置属性 <code>exports.a = a;</code></p>
</li>
<li><p>使用module.exports时，既单个设置属性 <code>module.exports.a</code>，也可以整个赋值 <code>module.exports = obj</code>。</p>
</li>
</ul>
<p>其他要点：</p>
<ul>
<li><p>Node中每个模块的最后，都会执行 <code>return: module.exports</code>。</p>
</li>
<li><p>Node中每个模块都会把 <code>module.exports</code>指向的对象赋值给一个变量 <code>exports</code>，也就是说 <code>exports = module.exports</code>。</p>
</li>
<li><p><code>module.exports = XXX</code>，表示当前模块导出一个单一成员，结果就是XXX。</p>
</li>
<li><p>如果需要导出多个成员，则必须使用 <code>exports.add = XXX; exports.foo = XXX</code>。或者使用 <code>module.exports.add = XXX; module.export.foo = XXX</code>。</p>
</li>
</ul>
<h3 id="问题-暴露的模块到底是谁？"><a href="#问题-暴露的模块到底是谁？" class="headerlink" title="问题: 暴露的模块到底是谁？"></a>问题: 暴露的模块到底是谁？</h3><p><strong>答案</strong>：暴露的本质是<code>exports</code>对象。【重要】</p>
<p>比如，方式一的 <code>exports.a = a</code> 可以理解成是，<strong>给 exports 对象添加属性</strong>。方式二的 <code>module.exports = a</code>可以理解成是给整个 exports 对象赋值。方式二的 <code>module.exports.c = c</code>可以理解成是给 exports 对象添加属性。</p>
<p>Node.js 中每个模块都有一个 module 对象，module 对象中的有一个 exports 属性称之为<strong>接口对象</strong>。我们需要把模块之间公共的方法或属性挂载在这个接口对象中，方便其他的模块使用。</p>
<h3 id="引入模块的方式：require"><a href="#引入模块的方式：require" class="headerlink" title="引入模块的方式：require"></a>引入模块的方式：require</h3><p>require函数用来在一个模块中引入另外一个模块。传入模块名，返回模块导出对象。</p>
<p><strong>语法格式</strong>：</p>
<pre class="highlight"><span class="line"><span class="keyword">const</span> module1 = <span class="built_in">require</span>(<span class="string">&#x27;模块名&#x27;</span>);</span><br></pre>

<p>解释：</p>
<ul>
<li><p>内置模块：require的是<strong>包名</strong>。</p>
</li>
<li><p>下载的第三方模块：require的是<strong>包名</strong>。</p>
</li>
<li><p>自定义模块：require的是<strong>文件路径</strong>。文件路径既可以用绝对路径，也可以用相对路径。后缀名<code>.js</code>可以省略。</p>
</li>
</ul>
<p><strong>代码举例</strong>：</p>
<pre class="highlight"><span class="line"><span class="keyword">const</span> module1 = <span class="built_in">require</span>(<span class="string">&#x27;./main.js&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> module2 = <span class="built_in">require</span>(<span class="string">&#x27;./main&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> module3 = <span class="built_in">require</span>(<span class="string">&#x27;Demo/src/main.js&#x27;</span>);</span><br></pre>

<p><strong>require()函数的两个作用</strong>：</p>
<ul>
<li><p>执行导入的模块中的代码。</p>
</li>
<li><p>返回导入模块中的接口对象。</p>
</li>
</ul>
<h3 id="主模块"><a href="#主模块" class="headerlink" title="主模块"></a>主模块</h3><p>主模块是整个程序执行的入口，可以调度其他模块。</p>
<pre class="highlight"><span class="line"><span class="comment"># 运行main.js启动程序。此时，main.js就是主模块</span></span><br><span class="line">$ node main.js</span><br></pre>

<h3 id="模块的初始化"><a href="#模块的初始化" class="headerlink" title="模块的初始化"></a>模块的初始化</h3><p>一个模块中的 JS 代码仅在模块<strong>第一次被使用时</strong>执行一次，并且在使用的过程中进行初始化，然后会被缓存起来，便于后续继续使用。</p>
<p>代码举例：</p>
<p>（1）calModule.js:</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> a = <span class="number">1</span>;</span><br><span class="line">​</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">add</span> () &#123;</span><br><span class="line">  <span class="keyword">return</span> ++a;</span><br><span class="line">&#125;</span><br><span class="line">​</span><br><span class="line"><span class="built_in">exports</span>.<span class="property">add</span> = add;</span><br><span class="line"></span><br></pre>

<p>（2）main.js：（在 main.js 中引入 hello.js 模块）</p>
<pre class="highlight"><span class="line"><span class="keyword">var</span> addModule1 = <span class="built_in">require</span>(<span class="string">&#x27;./calModule&#x27;</span>)</span><br><span class="line"><span class="keyword">var</span> addModule2 = <span class="built_in">require</span>(<span class="string">&#x27;./calModule&#x27;</span>)</span><br><span class="line">​</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(addModule1.<span class="title function_">add</span>());</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(addModule2.<span class="title function_">add</span>());</span><br></pre>

<p>在命令行执行 <code>node main.js</code> 运行程序，打印结果：</p>
<pre class="highlight"><span class="line">2</span><br><span class="line">3</span><br></pre>

<p>从打印结果中可以看出，<code>calModule.js</code>这个模块虽然被引用了两次，但只初始化了一次。</p>
<h2 id="CommonJS-在服务器端的实现举例"><a href="#CommonJS-在服务器端的实现举例" class="headerlink" title="CommonJS 在服务器端的实现举例"></a>CommonJS 在服务器端的实现举例</h2><h3 id="1、初始化项目"><a href="#1、初始化项目" class="headerlink" title="1、初始化项目"></a>1、初始化项目</h3><p>在工程文件中新建如下目录和文件：</p>
<pre class="highlight"><span class="line">modules</span><br><span class="line">    | module1.js</span><br><span class="line">    | module2.js</span><br><span class="line">    | module3.js</span><br><span class="line"></span><br><span class="line">app.js</span><br></pre>

<p>然后在根目录下新建如下命令：</p>
<pre class="highlight"><span class="line">npm init</span><br></pre>


<p>然后根据提示，依次输入如下内容：</p>
<ul>
<li><p><strong>包名</strong>：可以自己起包名，也可以用默认的包名。注意，包名里不能有中文，不能有大写。</p>
</li>
<li><p><strong>版本</strong>：可以用默认的版本 1.0.0，也可以自己修改包名。</p>
</li>
</ul>
<p>其他的参数，一路回车即可。效果如下：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20180410_1425.png" class="lozad post-image"src="http://img.smyhvae.com/20180410_1425.png"></p>
<p>于是，根目录下会自动生成<code>package.json</code>这个文件。点进去看一下：</p>
<pre class="highlight"><span class="line"><span class="punctuation">&#123;</span></span><br><span class="line">  <span class="attr">&quot;name&quot;</span><span class="punctuation">:</span> <span class="string">&quot;commonjs_node&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;version&quot;</span><span class="punctuation">:</span> <span class="string">&quot;1.0.0&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;description&quot;</span><span class="punctuation">:</span> <span class="string">&quot;&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;main&quot;</span><span class="punctuation">:</span> <span class="string">&quot;app.js&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;scripts&quot;</span><span class="punctuation">:</span> <span class="punctuation">&#123;</span></span><br><span class="line">    <span class="attr">&quot;test&quot;</span><span class="punctuation">:</span> <span class="string">&quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;</span></span><br><span class="line">  <span class="punctuation">&#125;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;author&quot;</span><span class="punctuation">:</span> <span class="string">&quot;smyhvae&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;license&quot;</span><span class="punctuation">:</span> <span class="string">&quot;ISC&quot;</span></span><br><span class="line"><span class="punctuation">&#125;</span></span><br><span class="line"></span><br></pre>


<h3 id="2、导入第三方包"><a href="#2、导入第三方包" class="headerlink" title="2、导入第三方包"></a>2、导入第三方包</h3><p><code>uniq</code>这个第三方包的作用是保证唯一性（我们拿它来举例）。我们在当前工程目录下，输入如下命令进行安装：</p>
<pre class="highlight"><span class="line">npm install uniq</span><br></pre>

<p>安装成功后，根目录下会自动生成相应的文件：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20180410_1450.png" class="lozad post-image"src="http://img.smyhvae.com/20180410_1450.png"></p>
<p>需要说明的是，我的node版本是 v8.10.0（v8以上），对应的 npm 版本是 v5.6.0，版本比较高，因此，当我输入完<code>npm install uniq</code>之后，<code>package.json</code>中就会自动添加<code>uniq</code>包的依赖：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20180410_1855.png" class="lozad post-image"src="http://img.smyhvae.com/20180410_1855.png"></p>
<p>如果有些童鞋的npm版本较低，就需要手动去添加依赖；另一种方式是，可以使用<code>npm install uniq --save</code>命令，这个多出来的<code>--save</code>就可以自动添加依赖。</p>
<p>我们去<a target="_blank" rel="noopener" href="https://www.npmjs.com/package/uniq">官网</a>看一下<code>uniq</code>的用法：</p>
<pre class="highlight"><span class="line"><span class="keyword">let</span> uniq = <span class="built_in">require</span>(<span class="string">&#x27;uniq&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> arr = [<span class="number">1</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">5</span>];</span><br><span class="line"><span class="title function_">uniq</span>(arr);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(arr);  <span class="comment">//输出结果：[ 1, 2, 3, 5 ]</span></span><br><span class="line"></span><br></pre>

<p>可以看出，这个包可以起到数组去重的作用。</p>
<h3 id="3、自定义模块"><a href="#3、自定义模块" class="headerlink" title="3、自定义模块"></a>3、自定义模块</h3><p>（1）module1.js：</p>
<pre class="highlight"><span class="line"><span class="comment">//暴露方式一：module.exports = value</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//暴露一个对象出去</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = &#123;</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&#x27;我是 module1&#x27;</span>,</span><br><span class="line">    <span class="title function_">foo</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">name</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//我们不能再继续写 module.exports = xxx。因为重新赋值，会把之前的赋值覆盖掉。</span></span><br><span class="line"></span><br></pre>

<p>（2）module2.js：</p>
<pre class="highlight"><span class="line"><span class="comment">//暴露方式一：module.exports = value</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//暴露一个函数出去</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = <span class="keyword">function</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;我是 module2&#x27;</span>);</span><br><span class="line">&#125;</span><br></pre>

<p>注意，此时暴露出去的 exports 对象 等价于整个函数。</p>
<p>（3）module3.js：</p>
<pre class="highlight"><span class="line"><span class="comment">//暴露方式二：exports.xxx = value</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//可以往 export 对象中不断地添加属性，进行暴露</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">exports</span>.<span class="property">foo1</span> = <span class="keyword">function</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;module3 中的 foo1 方法&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">exports</span>.<span class="property">foo2</span> = <span class="keyword">function</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;module3 中的 foo2 方法&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">exports</span>.<span class="property">arr</span> = [<span class="number">1</span>,<span class="number">1</span>,<span class="number">2</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">5</span>,<span class="number">11</span>];</span><br><span class="line"></span><br></pre>

<p>（4）app.js：（将其他模块汇集到主模块）</p>
<pre class="highlight"><span class="line"><span class="comment">//将其他模块汇集到主模块</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> uniq = <span class="built_in">require</span>(<span class="string">&#x27;uniq&#x27;</span>); <span class="comment">//引入时，第三方模块要放在自定义模块的上面</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> module1 = <span class="built_in">require</span>(<span class="string">&#x27;./modules/module1&#x27;</span>);</span><br><span class="line"><span class="keyword">let</span> module2 = <span class="built_in">require</span>(<span class="string">&#x27;./modules/module2&#x27;</span>);</span><br><span class="line"><span class="keyword">let</span> module3 = <span class="built_in">require</span>(<span class="string">&#x27;./modules/module3&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//调用module1对象的方法</span></span><br><span class="line">module1.<span class="title function_">foo</span>();</span><br><span class="line"></span><br><span class="line"><span class="comment">//调用module2的函数</span></span><br><span class="line"><span class="title function_">module2</span>();  <span class="comment">//注意，在定义时，module2对象等价于整个函数function。所以，module2()的意思是，直接调用了函数。</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//调用module3中的属性</span></span><br><span class="line">module3.<span class="title function_">foo1</span>();</span><br><span class="line">module3.<span class="title function_">foo2</span>();</span><br><span class="line"></span><br><span class="line"><span class="title function_">uniq</span>(module3.<span class="property">arr</span>); <span class="comment">//将module3中的数组进行去重操作</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(module3.<span class="property">arr</span>); <span class="comment">//打印数组去重后的结果</span></span><br></pre>

<p>这样的话，我们的代码就写完了。</p>
<p>我们在命令行中输入<code>node app.js</code>，就可以把代码跑起来了。打印结果如下：</p>
<pre class="highlight"><span class="line">我是 module1</span><br><span class="line">我是 module2</span><br><span class="line">module3 中的 foo1 方法</span><br><span class="line">module3 中的 foo2 方法</span><br><span class="line">[ 1, 11, 2, 3, 5 ]</span><br><span class="line"></span><br></pre>


<h2 id="CommonJS-基于浏览器端的实现举例"><a href="#CommonJS-基于浏览器端的实现举例" class="headerlink" title="CommonJS 基于浏览器端的实现举例"></a>CommonJS 基于浏览器端的实现举例</h2><h3 id="1、初始化项目-1"><a href="#1、初始化项目-1" class="headerlink" title="1、初始化项目"></a>1、初始化项目</h3><p>在工程文件中新建如下目录和文件：</p>
<pre class="highlight"><span class="line">js</span><br><span class="line">    dist //打包生成文件的目录</span><br><span class="line">    src //源码所在的目录</span><br><span class="line">      | module1.js</span><br><span class="line">      | module2.js</span><br><span class="line">      | module3.js</span><br><span class="line">      | app.js //应用主源文件</span><br><span class="line">index.html    //因为CommonJS是基于浏览器端，js文件要跑在浏览器的页面上，所以要有这个html页面</span><br></pre>

<p>然后在根目录下新建如下命令：</p>
<pre class="highlight"><span class="line">npm init</span><br></pre>


<p>然后根据提示，依次输入如下内容：</p>
<ul>
<li><p><strong>包名</strong>：可以自己起包名，也可以用默认的包名。注意，包名里不能有中文，不能有大写。</p>
</li>
<li><p><strong>版本</strong>：可以用默认的版本 1.0.0，也可以自己修改包名。</p>
</li>
</ul>
<p>其他的参数，一路回车即可。</p>
<p>于是，根目录下会自动生成<code>package.json</code>这个文件。点进去看一下：</p>
<pre class="highlight"><span class="line"><span class="punctuation">&#123;</span></span><br><span class="line">  <span class="attr">&quot;name&quot;</span><span class="punctuation">:</span> <span class="string">&quot;commonjs_browser&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;version&quot;</span><span class="punctuation">:</span> <span class="string">&quot;1.0.0&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;description&quot;</span><span class="punctuation">:</span> <span class="string">&quot;&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;main&quot;</span><span class="punctuation">:</span> <span class="string">&quot;index.js&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;scripts&quot;</span><span class="punctuation">:</span> <span class="punctuation">&#123;</span></span><br><span class="line">    <span class="attr">&quot;test&quot;</span><span class="punctuation">:</span> <span class="string">&quot;echo \&quot;Error: no test specified\&quot; &amp;&amp; exit 1&quot;</span></span><br><span class="line">  <span class="punctuation">&#125;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;author&quot;</span><span class="punctuation">:</span> <span class="string">&quot;&quot;</span><span class="punctuation">,</span></span><br><span class="line">  <span class="attr">&quot;license&quot;</span><span class="punctuation">:</span> <span class="string">&quot;ISC&quot;</span></span><br><span class="line"><span class="punctuation">&#125;</span></span><br><span class="line"></span><br><span class="line"></span><br></pre>


<h3 id="2、下载第三方包：Browserify"><a href="#2、下载第三方包：Browserify" class="headerlink" title="2、下载第三方包：Browserify"></a>2、下载第三方包：Browserify</h3><p>这里需要用到<a target="_blank" rel="noopener" href="http://browserify.org/">Browserify</a>这个工具进行编译打包。Browserify 称为 CommonJS 的浏览器端的打包工具。</p>
<p>输入如下命令进行安装：（两个命令都要输入）</p>
<pre class="highlight"><span class="line">npm install browserify -g          <span class="comment">//全局</span></span><br><span class="line">npm install browserify --save-dev  <span class="comment">//局部。</span></span><br></pre>

<p>上面的代码中，<code>-dev</code>表示开发依赖。这里解释一下相关概念：</p>
<ul>
<li><p>开发依赖：当前这个包，只在开发环境下使用。</p>
</li>
<li><p>运行依赖：当前这个包，是在生产环境下使用。</p>
</li>
</ul>
<h3 id="3、自定义模块-amp-代码运行"><a href="#3、自定义模块-amp-代码运行" class="headerlink" title="3、自定义模块 &amp; 代码运行"></a>3、自定义模块 &amp; 代码运行</h3><p>（1）module1.js：</p>
<pre class="highlight"><span class="line"><span class="comment">//暴露方式一：module.exports = value</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//暴露一个对象出去</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = &#123;</span><br><span class="line">    <span class="attr">name</span>: <span class="string">&#x27;我是 module1&#x27;</span>,</span><br><span class="line">    <span class="title function_">foo</span>(<span class="params"></span>)&#123;</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">name</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//我们不能再继续写 module.exports = xxx。因为重新赋值，会把之前的赋值覆盖掉。</span></span><br><span class="line"></span><br></pre>

<p>（2）module2.js：</p>
<pre class="highlight"><span class="line"><span class="comment">//暴露方式一：module.exports = value</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//暴露一个函数出去</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = <span class="keyword">function</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;我是 module2&#x27;</span>);</span><br><span class="line">&#125;</span><br></pre>

<p>注意，此时暴露出去的 exports 对象 等价于整个函数。</p>
<p>（3）module3.js：</p>
<pre class="highlight"><span class="line"><span class="comment">//暴露方式二：exports.xxx = value</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//可以往export对象中不断地添加属性，进行暴露</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">exports</span>.<span class="property">foo1</span> = <span class="keyword">function</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;module3 中的 foo1 方法&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">exports</span>.<span class="property">foo2</span> = <span class="keyword">function</span>(<span class="params"></span>)&#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;module3 中的 foo2 方法&#x27;</span>);</span><br><span class="line">&#125;</span><br></pre>

<p>（4）app.js：（将其他模块汇集到主模块）</p>
<pre class="highlight"><span class="line"><span class="keyword">let</span> module1 = <span class="built_in">require</span>(<span class="string">&#x27;./module1&#x27;</span>);  <span class="comment">// ./ 指的是当前路径</span></span><br><span class="line"><span class="keyword">let</span> module2 = <span class="built_in">require</span>(<span class="string">&#x27;./module2&#x27;</span>);</span><br><span class="line"><span class="keyword">let</span> module3 = <span class="built_in">require</span>(<span class="string">&#x27;./module3&#x27;</span>);</span><br><span class="line"></span><br><span class="line">module1.<span class="title function_">foo</span>();</span><br><span class="line"><span class="title function_">module2</span>();</span><br><span class="line">module3.<span class="title function_">foo1</span>();</span><br><span class="line">module3.<span class="title function_">foo2</span>();</span><br></pre>

<p>引入的路径解释：</p>
<ul>
<li><code>./</code>是相对路径，指的是当前路径（app.js的当前路径是src）</li>
</ul>
<p>到此，我们的主要代码就写完了。</p>
<p>但是，如果我们直接在index.html中，像下面这样写，是不行的：（因为浏览器不认识 require 关键字）</p>
<pre class="highlight"><span class="line"><span class="meta">&lt;!DOCTYPE <span class="keyword">html</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">&quot;en&quot;</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">&quot;UTF-8&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">&quot;viewport&quot;</span> <span class="attr">content</span>=<span class="string">&quot;width=device-width, initial-scale=1.0&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">&quot;X-UA-Compatible&quot;</span> <span class="attr">content</span>=<span class="string">&quot;ie=edge&quot;</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Document<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">&quot;./js/src/app.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br><span class="line"></span><br></pre>

<p>为了能够让index.html引入app.js，我们需要输入如下命令：</p>
<p>打包处理js:</p>
<pre class="highlight"><span class="line">browserify js/src/app.js -o js/dist/bundle.js</span><br></pre>

<p>然后在index.html中引入打包后的文件：</p>
<pre class="highlight"><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">&quot;text/javascript&quot;</span> <span class="attr">src</span>=<span class="string">&quot;js/dist/bundle.js&quot;</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre>
















  </div>
  <div>
    
      <div 
        class="post-note note-warning copyright" 
        style="margin-top: 42px">
        <p>
          <span style="font-weight: bold;">作者：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="/about">
            zwl5670
          </a>
        </p>
        <p>
          <span style="font-weight: bold;">文章链接：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="https://zwl5670.gitee.io/2011/08/01/11-Node.js/04-Node.js%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83%EF%BC%9ACommonJS/">
            https://zwl5670.gitee.io/2011/08/01/11-Node.js/04-Node.js%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83%EF%BC%9ACommonJS/
          </a>
        </p>
        <p><span style="font-weight: bold;">版权声明：</span>本博客所有文章除特别声明外，均采用<a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">CC BY-NC-SA 4.0 协议</a>。转载请注明出处！</p>
      </div>
    
  </div>
</article>
<div class="nav">
  
    <div class="nav-item-prev">
      <a 
        href="/2011/08/01/11-Node.js/03-Node.js%E5%BC%80%E5%8F%91%E7%8E%AF%E5%A2%83%E5%AE%89%E8%A3%85/" 
        class="nav-link">
        <i class="iconfont icon-left nav-prev-icon"></i>
        <div>
          <div class="nav-label">上一篇</div>
          
            <div class="nav-title">03-Node.js开发环境安装 </div>
          
        </div>
      </a>
    </div>
  
  
    <div class="nav-item-next">
      <a 
        href="/2011/08/01/11-Node.js/05-Node.js%E5%86%85%E7%BD%AE%E6%A8%A1%E5%9D%97%EF%BC%9Afs%E6%96%87%E4%BB%B6%E6%A8%A1%E5%9D%97/" 
        class="nav-link">
        <div>
          <div class="nav-label">下一篇</div>
          
            <div class="nav-title">05-Node.js内置模块：fs文件模块 </div>
          
        </div>
        <i class="iconfont icon-right nav-next-icon"></i>
      </a>
    </div>
  
</div>

<div 
  class="card card-content toc-card" 
  id="mobiletoc">
  <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-text">前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E7%9A%84%E7%90%86%E8%A7%A3"><span class="toc-text">模块化的理解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E6%A8%A1%E5%9D%97%E5%8C%96"><span class="toc-text">什么是模块化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E7%9A%84%E5%A5%BD%E5%A4%84"><span class="toc-text">模块化的好处</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83"><span class="toc-text">模块化规范</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83%E7%9A%84%E5%BC%95%E5%85%A5"><span class="toc-text">模块化规范的引入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E7%9A%84%E6%A6%82%E5%BF%B5%E8%A7%A3%E8%AF%BB"><span class="toc-text">模块化的概念解读</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83-1"><span class="toc-text">模块化规范</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CommonJS-%E7%9A%84%E5%9F%BA%E6%9C%AC%E8%AF%AD%E6%B3%95"><span class="toc-text">CommonJS 的基本语法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#CommonJS-%E7%9A%84%E4%BB%8B%E7%BB%8D"><span class="toc-text">CommonJS 的介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E7%9A%84%E6%9A%B4%E9%9C%B2%E5%92%8C%E5%BC%95%E5%85%A5"><span class="toc-text">模块的暴露和引入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9A%B4%E9%9C%B2%E6%A8%A1%E5%9D%97%E7%9A%84%E6%96%B9%E5%BC%8F%E4%B8%80%EF%BC%9A-exports"><span class="toc-text">暴露模块的方式一： exports</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9A%B4%E9%9C%B2%E6%A8%A1%E5%9D%97%E7%9A%84%E6%96%B9%E5%BC%8F%E4%BA%8C%EF%BC%9A-module-exports"><span class="toc-text">暴露模块的方式二： module.exports</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#exports-%E5%92%8C-module-exports-%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-text">exports 和 module.exports 的区别</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%97%AE%E9%A2%98-%E6%9A%B4%E9%9C%B2%E7%9A%84%E6%A8%A1%E5%9D%97%E5%88%B0%E5%BA%95%E6%98%AF%E8%B0%81%EF%BC%9F"><span class="toc-text">问题: 暴露的模块到底是谁？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%95%E5%85%A5%E6%A8%A1%E5%9D%97%E7%9A%84%E6%96%B9%E5%BC%8F%EF%BC%9Arequire"><span class="toc-text">引入模块的方式：require</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BB%E6%A8%A1%E5%9D%97"><span class="toc-text">主模块</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E7%9A%84%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-text">模块的初始化</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CommonJS-%E5%9C%A8%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%AB%AF%E7%9A%84%E5%AE%9E%E7%8E%B0%E4%B8%BE%E4%BE%8B"><span class="toc-text">CommonJS 在服务器端的实现举例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%88%9D%E5%A7%8B%E5%8C%96%E9%A1%B9%E7%9B%AE"><span class="toc-text">1、初始化项目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E5%AF%BC%E5%85%A5%E7%AC%AC%E4%B8%89%E6%96%B9%E5%8C%85"><span class="toc-text">2、导入第三方包</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E6%A8%A1%E5%9D%97"><span class="toc-text">3、自定义模块</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CommonJS-%E5%9F%BA%E4%BA%8E%E6%B5%8F%E8%A7%88%E5%99%A8%E7%AB%AF%E7%9A%84%E5%AE%9E%E7%8E%B0%E4%B8%BE%E4%BE%8B"><span class="toc-text">CommonJS 基于浏览器端的实现举例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%88%9D%E5%A7%8B%E5%8C%96%E9%A1%B9%E7%9B%AE-1"><span class="toc-text">1、初始化项目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E4%B8%8B%E8%BD%BD%E7%AC%AC%E4%B8%89%E6%96%B9%E5%8C%85%EF%BC%9ABrowserify"><span class="toc-text">2、下载第三方包：Browserify</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E6%A8%A1%E5%9D%97-amp-%E4%BB%A3%E7%A0%81%E8%BF%90%E8%A1%8C"><span class="toc-text">3、自定义模块 &amp; 代码运行</span></a></li></ol></li></ol>
</div>
            </main>
            <aside class="right-column">
              <div class="sticky-widescreen">
  
  
    <article class="card card-content toc-card">
      <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%89%8D%E8%A8%80"><span class="toc-text">前言</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E7%9A%84%E7%90%86%E8%A7%A3"><span class="toc-text">模块化的理解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E6%A8%A1%E5%9D%97%E5%8C%96"><span class="toc-text">什么是模块化</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E7%9A%84%E5%A5%BD%E5%A4%84"><span class="toc-text">模块化的好处</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83"><span class="toc-text">模块化规范</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83%E7%9A%84%E5%BC%95%E5%85%A5"><span class="toc-text">模块化规范的引入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E7%9A%84%E6%A6%82%E5%BF%B5%E8%A7%A3%E8%AF%BB"><span class="toc-text">模块化的概念解读</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96%E8%A7%84%E8%8C%83-1"><span class="toc-text">模块化规范</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CommonJS-%E7%9A%84%E5%9F%BA%E6%9C%AC%E8%AF%AD%E6%B3%95"><span class="toc-text">CommonJS 的基本语法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#CommonJS-%E7%9A%84%E4%BB%8B%E7%BB%8D"><span class="toc-text">CommonJS 的介绍</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E7%9A%84%E6%9A%B4%E9%9C%B2%E5%92%8C%E5%BC%95%E5%85%A5"><span class="toc-text">模块的暴露和引入</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9A%B4%E9%9C%B2%E6%A8%A1%E5%9D%97%E7%9A%84%E6%96%B9%E5%BC%8F%E4%B8%80%EF%BC%9A-exports"><span class="toc-text">暴露模块的方式一： exports</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%9A%B4%E9%9C%B2%E6%A8%A1%E5%9D%97%E7%9A%84%E6%96%B9%E5%BC%8F%E4%BA%8C%EF%BC%9A-module-exports"><span class="toc-text">暴露模块的方式二： module.exports</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#exports-%E5%92%8C-module-exports-%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="toc-text">exports 和 module.exports 的区别</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%97%AE%E9%A2%98-%E6%9A%B4%E9%9C%B2%E7%9A%84%E6%A8%A1%E5%9D%97%E5%88%B0%E5%BA%95%E6%98%AF%E8%B0%81%EF%BC%9F"><span class="toc-text">问题: 暴露的模块到底是谁？</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%95%E5%85%A5%E6%A8%A1%E5%9D%97%E7%9A%84%E6%96%B9%E5%BC%8F%EF%BC%9Arequire"><span class="toc-text">引入模块的方式：require</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BB%E6%A8%A1%E5%9D%97"><span class="toc-text">主模块</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E7%9A%84%E5%88%9D%E5%A7%8B%E5%8C%96"><span class="toc-text">模块的初始化</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CommonJS-%E5%9C%A8%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%AB%AF%E7%9A%84%E5%AE%9E%E7%8E%B0%E4%B8%BE%E4%BE%8B"><span class="toc-text">CommonJS 在服务器端的实现举例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%88%9D%E5%A7%8B%E5%8C%96%E9%A1%B9%E7%9B%AE"><span class="toc-text">1、初始化项目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E5%AF%BC%E5%85%A5%E7%AC%AC%E4%B8%89%E6%96%B9%E5%8C%85"><span class="toc-text">2、导入第三方包</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E6%A8%A1%E5%9D%97"><span class="toc-text">3、自定义模块</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#CommonJS-%E5%9F%BA%E4%BA%8E%E6%B5%8F%E8%A7%88%E5%99%A8%E7%AB%AF%E7%9A%84%E5%AE%9E%E7%8E%B0%E4%B8%BE%E4%BE%8B"><span class="toc-text">CommonJS 基于浏览器端的实现举例</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1%E3%80%81%E5%88%9D%E5%A7%8B%E5%8C%96%E9%A1%B9%E7%9B%AE-1"><span class="toc-text">1、初始化项目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2%E3%80%81%E4%B8%8B%E8%BD%BD%E7%AC%AC%E4%B8%89%E6%96%B9%E5%8C%85%EF%BC%9ABrowserify"><span class="toc-text">2、下载第三方包：Browserify</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3%E3%80%81%E8%87%AA%E5%AE%9A%E4%B9%89%E6%A8%A1%E5%9D%97-amp-%E4%BB%A3%E7%A0%81%E8%BF%90%E8%A1%8C"><span class="toc-text">3、自定义模块 &amp; 代码运行</span></a></li></ol></li></ol>
    </article>
  
  
  <article class="card card-content">
    <div class="recent-posts-card">
  <div class="recent-posts-header">
    <i 
      class="iconfont icon-wenzhang_huaban" 
      style="padding-right: 2px;">
    </i>最近文章
  </div>
  <div class="recent-posts-list">
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/11-React%20Navive%E5%88%9D%E8%AF%86/"><div class="recent-posts-item-content">11-React Navive初识</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/10-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E4%BD%BF%E7%94%A8customRequest%E6%96%B9%E6%B3%95%E8%87%AA%E5%AE%9A%E4%B9%89%E4%B8%8A%E4%BC%A0%E8%A1%8C%E4%B8%BA/"><div class="recent-posts-item-content">10-AntD框架的upload组件上传图片时使用customRequest方法自定义上传行为</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/09-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E9%81%87%E5%88%B0%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9D%91/"><div class="recent-posts-item-content">09-AntD框架的upload组件上传图片时遇到的一些坑</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/08-Ant%20Design%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8/"><div class="recent-posts-item-content">08-Ant Design的基本使用</div></a>
      </div>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
          </div>
        </div>
      </div>
    </div>
     
    <footer class="footer">
  <div class="footer-container">
    <div>
      <div class="footer-dsc">
        <span>
          Copyright ©
          
            2023
          
          
        </span>
        &nbsp;
        <a 
          href="/" 
          class="footer-link">
          前端面试
        </a>
      </div>
    </div>

    
      <div class="footer-dsc">
        
          Powered by
          <a 
            href="https://hexo.io/" 
            class="footer-link" 
            target="_blank" 
            rel="nofollow noopener noreferrer">
            &nbsp;Hexo
          </a>
        
        
          <span>&nbsp;|&nbsp;</span>
        
        
          Theme -
          <a 
            href="https://github.com/theme-kaze" 
            class="footer-link" 
            target="_blank"
            rel="nofollow noopener noreferrer">
            &nbsp;Kaze
          </a>
        
      </div>
    
    
    
    
</footer>
 
    
  <a 
    role="button" 
    id="scrollbutton" 
    class="basebutton" 
    aria-label="回到顶部">
    <i class="iconfont icon-arrowleft button-icon"></i>
  </a>

<a 
  role="button" 
  id="menubutton"
  aria-label="menu button"
  class="basebutton">
  <i class="iconfont icon-menu button-icon"></i>
</a>
<a 
  role="button" 
  id="popbutton" 
  class="basebutton" 
  aria-label="控制中心">
  <i class="iconfont icon-expand button-icon"></i>
</a>
<a 
  role="button" 
  id="darkbutton" 
  class="basebutton darkwidget" 
  aria-label="夜色模式">
  <i class="iconfont icon-weather button-icon"></i>
</a>
<a 
  role="button" 
  id="searchbutton" 
  class="basebutton searchwidget" 
  aria-label="搜索">
  <i class="iconfont icon-search button-icon"></i>
</a> 
     
     
     
      <script>
  var addImgLayout = function () {
    var img = document.querySelectorAll('.post-content img')
    var i
    for (i = 0; i < img.length; i++) {
      var wrapper = document.createElement('a')
      wrapper.setAttribute('href', img[i].getAttribute('data-src'))
      wrapper.setAttribute('aria-label', 'illustration')
      wrapper.style.cssText =
        'width: 100%; display: flex; justify-content: center;'
      if (img[i].alt) wrapper.dataset.caption = img[i].alt
      wrapper.dataset.nolink = true
      img[i].before(wrapper)
      wrapper.append(img[i])
      var divWrap = document.createElement('div')
      divWrap.classList.add('gallery')
      wrapper.before(divWrap)
      divWrap.append(wrapper)
    }
    baguetteBox.run('.gallery')
  }
</script>
<script>
  loadScript(
    "/js/lib/lightbox/baguetteBox.min.js",
    addImgLayout
  )
</script>
 
     
     
    <script src="/js/main.js"></script> 
     
    
      <script>
        var addLazyload = function () {
          var observer = lozad('.lozad', {
            load: function (el) {
              el.srcset = el.getAttribute('data-src')
            },
            loaded: function (el) {
              el.classList.add('loaded')
            },
          })
          observer.observe()
        }
      </script>
      <script>
        loadScript('/js/lib/lozad.min.js', addLazyload)
      </script>
    
    <script src="//instant.page/5.1.0" type="module"
      integrity="sha384-by67kQnR+pyfy8yWP4kPO12fHKRLHZPfEsiSXR8u2IKcTdxD805MGUXBzVPnkLHw"></script>
    
    
  </body>
</html>
